package org.luxor.common.netty.jdk.aio.server;

import org.luxor.common.netty.jdk.aio.server.handler.AcceptCompletionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(AsyncTimeServerHandler.class);

    private CountDownLatch latch;
    private AsynchronousServerSocketChannel servAsyncSocketChannel;

    /**
     * 初始化AIO，绑定监听端口
     */
    public AsyncTimeServerHandler(int port) {
        try {
            // 1、打开AsynchronousServerSocketChannel，用于监听客户端的连接
            servAsyncSocketChannel = AsynchronousServerSocketChannel.open();
            // 2、绑定监听端口，设置连接为非阻塞模式
            servAsyncSocketChannel.bind(new InetSocketAddress(port), 1024);

            System.out.println("The time server is start in port : " + port);
        } catch (Exception e) {
            log.error("创建异步非阻塞IO服务端网络通道并绑定监听接口.失败!", e);
            System.exit(1);
        }
    }

    @Override
    public void run() {
        // 初始化CountDownLatch对象,确保在完成一组正在执行的操作之前，允许当前的线程一直阻塞
        this.latch = new CountDownLatch(1);
        // 接收客户端的首次连接
        this.servAsyncSocketChannel.accept(this, new AcceptCompletionHandler());
        try {
            // 阻塞当前线程，防止服务端线程执行完成退出
            latch.await();
        } catch (InterruptedException e) {
            log.warn("异步非阻塞IO服务端处理器，出现锁异常", e);
        }
    }

    public AsynchronousServerSocketChannel getServAsyncSocketChannel() {
        return servAsyncSocketChannel;
    }

    public CountDownLatch getLatch() {
        return latch;
    }

}
